<template>
  <view class="container">
    <!-- 页面头部标题 -->
    <view class="new-page-header">
      <!-- 状态栏占位 -->
      <view class="new-status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <!-- 导航栏 -->
      <view class="new-nav-bar" :style="{ height: navBarHeight + 'px' }">
        <!-- 返回按钮 -->
        <view class="new-back-button" @click="goBack">
          <u-icon name="arrow-left" size="36" color="#ffffff"></u-icon>
        </view>
        <!-- 标题 -->
        <view class="new-header-title" :style="{ lineHeight: navBarHeight + 'px' }">支付</view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 设备信息 -->
      <view class="device-info">
        <view class="info-title">设备信息</view>
        <view class="info-row">
          <view class="info-label">设备名称</view>
          <view class="info-value">{{
            equipmentInfo.scene_type === 1 ? "陪护床" : "轮椅"
          }}</view>
        </view>
        <view class="info-row">
          <view class="info-label">设备编号</view>
          <view class="info-value">{{ equipmentInfo.device_id }}</view>
        </view>
        <view class="info-row">
          <view class="info-label">开始时间</view>
          <view class="info-value">
            {{ startTime }}
            <!-- 2025年05月01日 -->
            <!-- <text class="time-highlight green">00时00分</text> -->
          </view>
        </view>
        <view class="info-row" v-if="equipmentInfo.scene_type === 1">
          <view class="info-label">到期时间</view>
          <view class="info-value">
            {{ endTime }}
            <!-- 2025年05月01日 -->
            <!-- <text class="time-highlight red">07时00分</text> -->
          </view>
        </view>
        <view class="info-row">
          <view class="info-label">收费标准</view>
          <!-- 如果是轮椅，小时收费 -->
          <view class="info-value" v-if="equipmentInfo.scene_type === 2">{{ orderInfoObj.hospital_price }}元/小时</view>
          <view class="info-value" v-else>{{ orderInfoObj.hospital_price }}元/次</view>
        </view>
        <view class="info-row">
          <view class="info-label">押金金额</view>
          <view class="info-value price">{{ depositAmount }}元</view>
        </view>

        <view class="info-row">
          <view class="info-label">预计金额</view>
          <view class="info-value price">{{ expectedAmount }}元</view>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="notice-info">
        <view class="notice-item">
          <text class="notice-star">*</text>
          <text class="notice-text">请在到期时间前归还</text>
        </view>
        <view class="notice-item">
          <text class="notice-star">*</text>
          <text class="notice-text">超时使用将按<text class="highlight">{{ orderInfoObj.overtime_money }}元/小时</text>
            <!-- 陪护床1 -->
            <text class="highlight" v-if="
              equipmentInfo.scene_type === 1 && hospitalInfoObj.capping_price
            ">扣费，封顶{{ hospitalInfoObj.capping_price }}元</text>
            <text class="highlight" v-else-if="
              equipmentInfo.scene_type === 2 &&
              hospitalInfoObj.wheelchair_capping_price
            ">扣费，日封顶{{
              hospitalInfoObj.wheelchair_capping_price
            }}元</text>
          </text>
        </view>
        <view class="notice-item">
          <text class="notice-star">*</text>
          <text class="notice-text">归还之后<text class="highlight">押金</text>将会原路返回</text>
        </view>
        <view class="notice-item">
          <text class="notice-star">*</text>
          <text class="notice-text">不足1小时按1小时收费</text>
        </view>
      </view>

      <!-- 支付按钮 -->
      <view class="payment-button">
        <view class="pay-btn" @click="handlePayment">
          <text class="pay-text">支付</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import navbarMixin from "@/common/mixin/navbar.js";
import { createOrder, reportPower } from "@/api/index";
import dayjs from "dayjs";
import store from "@/store";
// AES加密库（需要自行引入或实现）
const CryptoJS = require("crypto-js");
var fun_aes = require("utils/aes.js");

export default {
  mixins: [navbarMixin],

  data() {
    return {
      tokenCmd: [6, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
      // 扫码结果
      scanCode: "",
      // 扫码类型
      scanType: "rental",
      serviceId: "0000FEE7-0000-1000-8000-00805F9B34FB",
      writeCharId: "000036F5-0000-1000-8000-00805F9B34FB",
      readCharId: "0000FEC9-0000-1000-8000-00805F9B34FB",
      notifyCharId: "000036F6-0000-1000-8000-00805F9B34FB",
      devices: [],

      // 支付信息
      payInfo: {},

      // 设备名称
      deviceName: "",
      // 设备编号
      deviceNumber: "",
      // 开始时间
      startTime: "",
      // 结束时间
      endTime: "",
      // 收费标准
      chargeStandard: "",
      // 预计金额
      expectedAmount: "",
      // 押金金额
      depositAmount: "",

      // 当前设备对应的蓝牙mac
      currentDeviceMac: "",
      // 当前设备对应的设备id
      currentDeviceId: "",
      token: null,

      orderInfoObj: {},
      hospitalInfoObj: {},

      // 电量百分比
      batteryPercentage: 0,

      // 锁状态
      lockStatus: "",

      // 是否处于无蓝牙状态
      noBluetooth: false,

      // 主设备信息
      equipmentInfo: {},

      orderId: "",

      /* 蓝牙初始化中 */
      lanyaInitings: false,

      equipmentInfoObj: {},
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log("optionsoptionsoptionsoptions", options);


    if (options?.q) {
      var scene = decodeURIComponent(
        options?.q
      ); // 使用decodeURIComponent解析

      console.log("scenescenescenescenescenescenescenescenescene", scene);

      this.scanCode = scene?.split("/")?.[4];
    } else {
      this.scanCode = decodeURIComponent(options.code || "");


    }

    this.scanType = options.type || "rental";

    await this.getOrderInfo();

    await this.initBluetooth();
  },
  onUnload() {
    if (this.currentDeviceId) {
      uni.closeBLEConnection({ deviceId: this.currentDeviceId });
    }
  },

  methods: {
    // AES加密
    encryptData(data) {
      try {
        const aesKey = [
          0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f,
          0x4e, 0x0c, 0x13, 0x28, 0x25,
        ];
        const keyBytes = CryptoJS.enc.Utf8.parse(new Int8Array(aesKey));
        const dataBytes = CryptoJS.enc.Utf8.parse(data);
        // AES-128 ECB模式加密，无填充
        const encrypted = CryptoJS.AES.encrypt(dataBytes, keyBytes, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.NoPadding,
        });

        // 返回Uint8Array
        return new Int8Array(encrypted.ciphertext.words);
      } catch (e) {
        console.error("加密失败:", e);
        return null;
      }
    },
    aesEncrypt: function (array) {
      const INITIAL_KEY = [
        0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f, 0x4e,
        0x0c, 0x13, 0x28, 0x25,
      ];

      var acontent = array;
      var contentWA = fun_aes.CryptoJS.enc.int8array.parse(acontent);

      const key = fun_aes.CryptoJS.enc.int8array.parse(INITIAL_KEY);

      const encrypted = fun_aes.CryptoJS.AES.encrypt(contentWA, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.NoPadding,
      });

      var bv = fun_aes.CryptoJS.enc.int8array.stringify(encrypted.ciphertext);

      return bv;
    },
    // 解析广播数据
    parseAdvertData(buffer) {
      try {
        if (!buffer || buffer.byteLength < 9) return null;

        const dataView = new DataView(buffer);
        // 前2字节是PRO
        const PRO = dataView.getUint16(0, false).toString(16).padStart(4, "0");
        // 接下来6字节是MAC地址
        const MAC = Array.from({ length: 6 }, (_, i) =>
          dataView
            .getUint8(2 + i)
            .toString(16)
            .padStart(2, "0")
        ).join(":");
        // 第9字节是电量(0-100)
        const POWER = dataView.getUint8(8);
        // 第10字节是锁状态(如果有)
        const LOCK_STATE = buffer.byteLength > 9 ? dataView.getUint8(9) : null;

        return { PRO, MAC, POWER, LOCK_STATE };
      } catch (e) {
        console.error("解析广播数据失败:", e);
        return null;
      }
    },
    // 扫描设备
    scanDevices() {
      console.log("开始扫描设备...");
      this.devices = [];
      uni.startBluetoothDevicesDiscovery({
        // services: ["FEE7"],
        services: ["0000FEE7-0000-1000-8000-00805F9B34FB"],
        success: (res) => {
          console.log("扫描已启动", res);

          // 3秒后自动停止扫描
          setTimeout(() => {
            uni.stopBluetoothDevicesDiscovery();
            console.log("扫描已停止");
          }, 1000000);
        },
        fail: (err) => {
          console.log("扫描失败: " + JSON.stringify(err));
          this.lanyaInitings = false;
          console.log("errerr", err);
        },
      });
    },
    // 初始化蓝牙适配器
    initBluetooth() {
      // uni.hideLoading();
      this.lanyaInitings = true;
      // uni.showLoading({
      //   title: '初始化蓝牙设备中',
      // });
      const that = this;
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log("蓝牙适配器初始化成功");
          that.listenBluetoothEvents();

          setTimeout(() => {
            // 开始扫描
            that.scanDevices();
          }, 500);
        },
        fail: (err) => {
          console.log("蓝牙适配器初始化失败: " + JSON.stringify(err));
          // uni.showToast({
          //   title: "请打开蓝牙后重新扫码",
          //   icon: "none",
          // });
          that.noBluetooth = true;

          that.lanyaInitings = false;
        },
      });
    },
    arrayBufferToHexString: function (buffer) {
      if (buffer != "[object ArrayBuffer]") {
        return;
      }
      let dataView = new DataView(buffer);

      var hexStr = "";
      for (var i = 0; i < dataView.byteLength; i++) {
        var str = dataView.getUint8(i);
        var hex = (str & 0xff).toString(16);
        hex = hex.length === 1 ? "0" + hex : hex;
        hexStr += hex;
      }

      return hexStr.toUpperCase();
    },
    // 监听蓝牙事件
    listenBluetoothEvents() {
      console.log("开始监听蓝牙事件");

      // 监听蓝牙适配器状态变化
      // uni.onBluetoothAdapterStateChange((res) => {});

      // 监听设备发现事件
      uni.onBluetoothDeviceFound((res) => {
        console.log("resresresres", res);

        res.devices.forEach((device) => {
          if (!device.advertisData) return;

          // 解析广播数据
          // const parsedData = this.parseAdvertData(device.advertisData);

          var macAddressTmp = this.arrayBufferToHexString(device.advertisData);

          var tmpLength = macAddressTmp.length;

          if (tmpLength >= 16) {
            var macAddress =
              macAddressTmp.substring(4, 6) +
              ":" +
              macAddressTmp.substring(6, 8) +
              ":" +
              macAddressTmp.substring(8, 10) +
              ":" +
              macAddressTmp.substring(10, 12) +
              ":" +
              macAddressTmp.substring(12, 14) +
              ":" +
              macAddressTmp.substring(14, 16);
          }

          console.log("macAddress", macAddress);

          if (macAddress === this.currentDeviceMac) {
            console.log("找到对应的蓝牙设备拉", {
              macAddress,
              device: device,
            });

            this.currentDeviceId = device.deviceId;

            // 开始连接
            this.connectDevice(device.deviceId);
          }
        });
      });
    },
    bleGetToken: function () {
      //0x06	0x01	0x01	0x01
      const _token = [];
      const _that = this;
      for (let i = 0; i < _that.tokenCmd.length; i++) {
        if (i <= 3) {
          //
          _token.push(_that.tokenCmd[i]);
          continue;
        }
        const _num = Math.round(Math.random() * 100);
        _that.tokenCmd.splice(i, 1, _num);
        _token.push(_num);
      }

      _that.commDevice(_token);
    },
    // AES解密
    decryptData(data) {
      var that = this;
      var acontent = data;
      // 将密文转换成WordArray
      var contentWA = fun_aes.CryptoJS.enc.int8array.parse(acontent);
      // 插件要求密文是base64格式
      var dcBase64String = contentWA.toString(fun_aes.CryptoJS.enc.Base64);

      const INITIAL_KEY = [
        0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f, 0x4e,
        0x0c, 0x13, 0x28, 0x25,
      ];

      const key = fun_aes.CryptoJS.enc.int8array.parse(INITIAL_KEY);

      // 解密 选定mode是CFB类型，无偏移量
      var decrypted = fun_aes.CryptoJS.AES.decrypt(dcBase64String, key, {
        // iv: that.globalData.bleVariable.ivWA,
        mode: fun_aes.CryptoJS.mode.ECB,
        padding: fun_aes.CryptoJS.pad.NoPadding,
      });
      console.log("解密了，内容是=== " + decrypted);
      // 将解密后的明文转回int8数组
      var bv = fun_aes.CryptoJS.enc.int8array.stringify(decrypted);
      return bv;
    },

    // 等待Token响应
    waitForTokenResponse(timeout) {
      return new Promise((resolve) => {
        let timer;

        // 临时监听Token响应
        const handler = (res) => {
          console.log("接受token相应", res.value);

          const result = res.value;
          var resultArray = new Int8Array(result);

          const decrypted = this.decryptData(resultArray);

          console.log("接受到蓝牙的回调了哈", decrypted);

          if (!decrypted) return;

          // 检查是否为Token响应 (0x06 0x02)
          if (decrypted[0] == 6 && decrypted[1] == 2) {
            const _token = decrypted.slice(3, 7);

            clearTimeout(timer);
            uni.offBLECharacteristicValueChange(handler);

            this.getDeviceBattery(_token);

            /* 如果是1拖5 */
            if (this.equipmentInfo.hardware_type == 3) {
              this.getFiveLockStatus(_token);
            } else {
              this.queryLockStatus(_token);
            }

            resolve(_token); // 提取4字节Token
          } else if (
            decrypted[0] == 2 &&
            decrypted[1] == 2 &&
            decrypted[2] == 1
          ) {
            // 电量回调
            console.log("获取到电量了", decrypted[3]);

            this.batteryPercentage = decrypted[3];

            reportPower({
              device_code: this.scanCode,
              battery_level: decrypted[3],
            });
          } else if (
            decrypted[0] == 5 &&
            decrypted[1] == 15 &&
            decrypted[2] == 2
          ) {
            // 获取锁状态
            console.log("获取锁状态了", decrypted[4]);

            // 1标示关锁，0开锁
            this.lockStatus = decrypted[4];
          }
        };

        uni.onBLECharacteristicValueChange(handler);

        // 设置超时
        timer = setTimeout(() => {
          uni.offBLECharacteristicValueChange(handler);
          resolve(null);
        }, timeout);
      });
    },

    // 连接设备
    connectDevice(deviceId) {
      if (!deviceId) {
        console.log("请先选择设备");
        return;
      }

      uni.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
          this.getDeviceServices();
          console.log("连接成功", res);
          this.lanyaInitings = false;
        },
        fail: (err) => { },
      });
    },
    // 获取设备服务
    getDeviceServices() {
      const _that = this;
      uni.getBLEDeviceServices({
        deviceId: this.currentDeviceId,
        success: (res) => {
          this.getDeviceCharacteristics();

          console.log("获取蓝牙设备所有服务(service)", res);
        },
        fail: (err) => {
          console.log("获取服务失败: " + JSON.stringify(err));
        },
      });
    },
    async getToken() {
      try {
        const token = await this.waitForTokenResponse(500000);
        if (token) {
          this.token = token;
          // this.addLog(`获取Token成功: ${this.bytesToHex(this.token)}`);
        } else {
          throw new Error("获取Token超时");
        }
      } catch (err) {
        this.token = null;
      }
    },
    // 获取特征值
    getDeviceCharacteristics() {
      const _that = this;
      uni.getBLEDeviceCharacteristics({
        deviceId: this.currentDeviceId,
        serviceId: this.serviceId,
        success: (res) => {
          wx.onBLECharacteristicValueChange(function (characteristic) {
            console.log("监听特征值变化", characteristic);
          });

          wx.notifyBLECharacteristicValueChange({
            deviceId: this.currentDeviceId,
            serviceId: this.serviceId,
            characteristicId: this.notifyCharId,
            state: true,
            success: (res) => {
              console.log("已启用通知", res);
            },
            fail: (err) => {
              console.log("启用通知失败: " + JSON.stringify(err));
            },
            complete: (res) => {
              uni.onBLECharacteristicValueChange((res) => {
                console.log("接收到数据", res);
              });

              _that.getToken();
              setTimeout(() => {
                _that.bleGetToken();
              }, 500);
            },
            type: "notification",
          });
        },
        fail: (err) => { },
      });
    },

    /**
     * 与设备交互
     */
    commDevice: async function (cmd, type) {
      // 超时次数
      let timeoutCount = 0;

      const encrypted = this.aesEncrypt(cmd);

      await this.writeBLEValue(encrypted.buffer);

      // if (!type) {

      //   if (this.equipmentInfo.hardware_type === 1) {
      //     uni.showLoading({ title: '蓝牙设备初始化中...' });
      //   }

      //   // 等待Token响应 (超时5秒)
      //   const token = await this.waitForTokenResponse(5000);
      //   console.log('获取到了token啊啊啊啊啊', token);

      //   if (token) {
      //     this.token = token;
      //     uni.hideLoading();
      //   } else {

      //     if (timeoutCount < 3) {
      //       // 如果超时，设置一个超时次数，如果超过3次，则停止尝试获取Token
      //       this.bleGetToken();
      //     } else {
      //       timeoutCount += 1;
      //     }

      //     throw new Error('获取Token超时');

      //   }
      // } else {
      //   // 等待Token响应 (超时5秒)
      //   const _result = await this.waitForTokenResponse(5000);
      //   console.log(`获取到设备回调${type}`, _result);
      // }
    },

    async fiveUnlockDevice() {
      let _locakCmd = [5, 129, 9];

      let temp = [];

      if (this.equipmentInfoObj.nb_number == 1) {
        temp = [1, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 2) {
        temp = [2, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 3) {
        temp = [4, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 4) {
        temp = [8, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 5) {
        temp = [10, 0, 0];
      }

      /* 密码 */
      for (let i = 0; i <= 5; i++) {
        _locakCmd.push(48);
      }
      /* 掩码 */
      temp.forEach((item) => {
        _locakCmd.push(item);
      });

      this.token?.forEach((item) => {
        _locakCmd.push(item);
      });

      console.log("1拖5开锁 => ", _locakCmd);

      const encrypted = this.aesEncrypt(_locakCmd);
      if (!encrypted) {
        throw new Error("加密失败");
      }

      await this.writeBLEValue(encrypted.buffer);

      // const result = await this.waitCloseLock(50000);
    },

    // 开锁功能
    async unlockDevice() {
      let _locakCmd = [5, 1, 6];

      for (let i = 0; i <= 5; i++) {
        _locakCmd.push(48);
      }

      this.token.forEach((item) => {
        _locakCmd.push(item);
      });

      // 三个随机数
      for (let i = 0; i < 3; i++) {
        const _num = Math.round(Math.random() * 100);
        _locakCmd.push(_num);
      }

      const encrypted = this.aesEncrypt(_locakCmd);
      if (!encrypted) {
        throw new Error("加密失败");
      }

      await this.writeBLEValue(encrypted.buffer);

      const result = await this.waitCloseLock(50000);
    },

    async lockDevice() {
      let _locakCmd = [5, 12, 1, 1];

      this.token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      const encrypted = this.aesEncrypt(_locakCmd);
      if (!encrypted) {
        throw new Error("加密失败");
      }

      await this.writeBLEValue(encrypted.buffer);
    },
    // 获取设备电量
    async getDeviceBattery(token) {
      let _locakCmd = [2, 1, 1, 1];

      token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      this.commDevice(_locakCmd, "getDeviceBattery");
    },
    // 查询锁状态
    async queryLockStatus(token) {
      let _locakCmd = [5, 14, 1, 1];

      token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      this.commDevice(_locakCmd, "queryLockStatus");
    },
    /* 查询1拖5锁的状态 */
    async getFiveLockStatus(token) {
      let _locakCmd = [5, 142, 1, 1];

      token.forEach((item) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      this.commDevice(_locakCmd, "queryFiveLockStatus");
    },

    // 封装BLE写入操作
    writeBLEValue(value) {
      return new Promise((resolve, reject) => {
        uni.writeBLECharacteristicValue({
          deviceId: this.currentDeviceId,
          serviceId: this.serviceId,
          characteristicId: this.writeCharId,
          value: value,
          success: resolve,
          fail: reject,
        });
      });
    },
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 处理支付
     */
    handlePayment() {
      const _result = this.payInfo;

      if (this.equipmentInfo.hardware_type === 1) {
        // 如果是蓝牙设备
        if (!this.token) {
          return uni.showToast({
            title: "蓝牙正在连接设备中，请重试",
            icon: "none",
          });
        }
      }

      if (!this.noBluetooth && !this.token) {
        return uni.showToast({
          title: "蓝牙正在连接设备中，请重试",
          icon: "none",
        });
      }

      const _that = this;

      uni.showModal({
        title: "确认支付",
        content:
          this.equipmentInfo.scene_type === 1
            ? `确定要支付押金和租金${this.expectedAmount * 1}元吗？`
            : `确定要支付押金${this.expectedAmount * 1}元吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: "支付中...",
            });

            wx.requestPayment({
              timeStamp: _result?.timeStamp,
              nonceStr: _result.nonceStr,
              package: _result?.package,
              signType: _result?.signType,
              paySign: _result?.paySign,
              success(res) {
                console.log("res", res);
                uni.showToast({
                  title: "支付成功",
                });

                // 如果蓝牙未连接，则使用远程开锁
                if (_that.noBluetooth) {
                  // _that.unlockDevice();
                  // 请点击唤醒按钮
                  uni.showModal({
                    title: "提示",
                    content: "点击唤醒按钮即可开锁",
                    showCancel: false,
                    confirmText: "确定",
                    success() {
                      // 返回首页
                      setTimeout(() => {
                        // uni.switchTab({
                        //   url: '/pages/newindex/index',
                        // });
                        uni.reLaunch({
                          url: `/pages/newreturn/index?code=${_that.orderId}&type=return`,
                        });
                      }, 1000);
                    },
                  });
                } else {
                  // 如果是 NB锁，并且没有开蓝牙
                  if (_that.equipmentInfo.hardware_type == 2) {
                    _that.unlockDevice();

                    // 返回首页
                    setTimeout(() => {
                      uni.reLaunch({
                        url: `/pages/newreturn/index?code=${_that.orderId}&type=return`,
                      });
                    }, 1000);
                  } else if (_that.equipmentInfo.hardware_type == 3) {
                    _that.fiveUnlockDevice();

                    // 返回首页
                    setTimeout(() => {
                      uni.reLaunch({
                        url: `/pages/newreturn/index?code=${_that.orderId}&type=return`,
                      });
                    }, 1000);
                  } else if (_that.equipmentInfo.hardware_type == 1) {
                    _that.unlockDevice();

                    setTimeout(() => {
                      uni.reLaunch({
                        url: `/pages/newreturn/index?code=${_that.orderId}&type=return`,
                      });
                    }, 1000);
                  }
                }
                // orderId

                uni.hideLoading();
              },
              fail(res) {
                console.log("报错了", res);
                uni.hideLoading();
              },
            });
          }
        },
      });
    },
    // 通过设备id去创建订单
    async getOrderInfo() {
      try {
        const _res = await createOrder(
          {
            id: this.scanCode,
          },
          {
            isPrompt: false,
          }
        );

        console.log("结果", _res);

        this.equipmentInfo = _res?.equipment;

        this.orderInfoObj = _res.order;

        this.hospitalInfoObj = _res.$hospital;

        this.deviceName = _res?.equipment_info?.devicename;
        this.deviceNumber = _res?.equipment_info?.deviceno;
        this.equipmentInfoObj = _res?.equipment_info;
        // 使用day转换日期时间
        this.startTime = dayjs(_res?.order.createtime * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endTime = dayjs(_res?.order.answer_return_time * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.chargeStandard = _res?.order?.hospital_price;
        this.expectedAmount = _res?.order?.money;
        this.depositAmount = _res?.order.use_scene_type == 2 ? _res?.$hospital?.wheelchair_deposit : _res?.$hospital?.deposit_price;

        this.currentDeviceMac = _res?.equipment_info?.mac;

        this.$set(this, "payInfo", _res?.mentPay);

        this.orderId = _res.orderId;
      } catch (error) {
        console.log("error => ", error);
        if (error?.statusCode == 401) {
          store.dispatch("Logout");
          // 弹窗告诉用户去登录
          uni.showModal({
            title: "温馨提示",
            content: "此时此刻需要您登录喔~",
            showCancel: false,
            confirmText: "去登录",
            cancelText: "再逛会",
            // 隐藏cancel
            cancelButtonText: "",
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: "/pages/login/index",
                });
              }
              if (res.cancel && getCurrentPages().length > 1) {
                uni.navigateBack();
              }
            },
          });

          return;
        }
        uni.showModal({
          content: error.msg,
          // 确定按钮的文字
          confirmText: "知道了",
          showCancel: false,
          success: (success) => {
            /* 跳到pages/newindex/index */
            uni.switchTab({
              url: "/pages/newindex/index",
            });
          },
        });
      }
    },
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    return {
      title: "支付",
      path: "/pages/newpayment/index",
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f9fa;
}

.page-content {
  padding-bottom: 120rpx;
}

.device-info {
  background: #ffffff;
  margin: 30rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .info-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 30rpx;
  }

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      font-size: 28rpx;
      color: #666666;
    }

    .info-value {
      font-size: 28rpx;
      color: #333333;
      text-align: right;

      .time-highlight {
        &.green {
          color: #00b894;
          font-weight: 600;
        }

        &.red {
          color: #e74c3c;
          font-weight: 600;
        }
      }

      &.price {
        color: #e74c3c;
        font-weight: 600;
        font-size: 30rpx;
      }
    }
  }
}

.notice-info {
  margin: 0 30rpx 30rpx;
  padding: 30rpx;
  background: #fff3cd;
  border-radius: 20rpx;
  border-left: 8rpx solid #ffc107;

  .notice-item {
    display: flex;
    margin-bottom: 16rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .notice-star {
      color: #e74c3c;
      font-size: 24rpx;
      margin-right: 8rpx;
      margin-top: 2rpx;
    }

    .notice-text {
      font-size: 24rpx;
      color: #856404;
      line-height: 1.5;
      flex: 1;

      .highlight {
        color: #e74c3c;
        font-weight: 600;
      }
    }
  }
}

.payment-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 30rpx;
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);

  .pay-btn {
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
    height: 100rpx;
    border-radius: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 20rpx rgba(116, 185, 255, 0.4);

    .pay-text {
      font-size: 32rpx;
      color: #ffffff;
      font-weight: 600;
    }

    &:active {
      transform: scale(0.98);
      transition: transform 0.1s;
    }
  }
}
</style>
